﻿/*
  Please keep these information:
  From: http://wpfhelpertools.codeplex.com/ 
  Author: http://www.cnblogs.com/xiaokang088 
  Email: xiaokang060@hotmail.com
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading;
using System.Windows.Media.Animation;

namespace PublishTool
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region member variable
        string source = string.Empty,
            destination = string.Empty,
            prefix = string.Empty,
            folderNameDateFormat = string.Empty;
        List<string> selectedFiles = new List<string>(), selectedFolders = new List<string>();
        StringBuilder sbLog = new StringBuilder();
        string folderNameDefaultFormat = "yyyyMMdd HHmmss";
        #endregion

        #region constructor
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                List<string> allKeys = ConfigurationManager.AppSettings.Keys.OfType<string>().ToList();

                if (allKeys.Contains("Source"))
                    source = ConfigurationManager.AppSettings["Source"];

                if (allKeys.Contains("Destination"))
                {
                    destination = ConfigurationManager.AppSettings["Destination"];
                    if (destination.Contains("%"))
                    {
                        destination = Environment.ExpandEnvironmentVariables(destination);
                    }
                }
                if (allKeys.Contains("Prefix"))
                    prefix = ConfigurationManager.AppSettings["Prefix"];

                if (allKeys.Contains("Files"))
                    selectedFiles = ConfigurationManager.AppSettings["Files"].Split('|').ToList();

                if (allKeys.Contains("Folders"))
                    selectedFolders = ConfigurationManager.AppSettings["Folders"].Split('|').ToList();

                if (allKeys.Contains("FolderNameDateFormat"))
                    folderNameDateFormat = ConfigurationManager.AppSettings["FolderNameDateFormat"];
            }
            catch (Exception ex)
            {
                Trace.Write(ex);
                tb.Text = "Init Paras fail ！Please check config ";
                this.Close();
                return;
            }
            sbLog.AppendLine("1.Source:");
            sbLog.AppendLine(source);
            sbLog.AppendLine();
            sbLog.AppendLine("2.Destination:");
            sbLog.AppendLine(destination);

            sbLog.AppendLine();
            sbLog.AppendLine("3.Folders:");
            foreach (string str in selectedFolders)
                sbLog.AppendLine(str);

            sbLog.AppendLine();
            sbLog.AppendLine("4.Files:");
            foreach (string str in selectedFiles)
                sbLog.AppendLine(str);
            tb.Text = sbLog.ToString();
        }
        #endregion

        #region event handle
        private void btnPublish_Click(object sender, RoutedEventArgs e)
        {
            new Thread(new ThreadStart(Copy)).Start();
        }


        private void btnSource_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(source);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "    " + source);
            }
        }

        private void btnDestination_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(destination);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void Invoke(Action a)
        {
            this.Dispatcher.Invoke(a);

        }

        void Copy()
        {
            Invoke(() => mask.Visibility = System.Windows.Visibility.Visible);

            #region path
            StringBuilder path = new StringBuilder();
            if (destination.EndsWith(@"\"))
                path.Append(destination);
            else
            {
                path.Append(destination);
                path.Append(@"\");
            }
            path.Append(prefix);

            if (!string.IsNullOrEmpty(folderNameDateFormat))
            {
                try
                {
                    string folderName = DateTime.Now.ToString(folderNameDateFormat);
                    path.Append(folderName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    Debug.WriteLine(ex);
                }
            }
            #endregion

            #region create path
            string folderPath = path.ToString();
            try
            {
                if (Directory.Exists(folderPath))
                {
                    //Directory.Delete(folderPath);
                }
                else
                    Directory.CreateDirectory(folderPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Create Destination Fail!  " + ex.Message);
                return;
            }
            #endregion

            #region file copy
            if (!Directory.Exists(source))
            {
                MessageBox.Show("Directory is not exist:" + source);
                return;
            }

            try
            {
                string[] files = Directory.GetFiles(source, "*.*");
                foreach (string file in files)
                {
                    var fileName = System.IO.Path.GetFileName(file);
                    if (selectedFiles.Contains(fileName))
                        File.Copy(file, folderPath + "\\" + System.IO.Path.GetFileName(fileName));
                }

                string[] folders = Directory.GetDirectories(source, "*.*");
                foreach (string folder in folders)
                {
                    string subFolderName = System.IO.Path.GetFileName(folder);
                    if (selectedFolders.Contains(subFolderName))
                    {
                        string newSubFolderPath = string.Empty;
                        if (folderPath.EndsWith(@"\"))
                            newSubFolderPath = folderPath + subFolderName;
                        else
                            newSubFolderPath = folderPath + "\\" + subFolderName;
                        CopyDirectory(folder, newSubFolderPath);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Copy file Fail" + ex.Message);
                return;
            }
            #endregion

            Invoke(() => mask.Visibility = System.Windows.Visibility.Collapsed);

            System.Diagnostics.Process.Start(folderPath);
        }

        void CopyDirectory(string oldDirectory, string newDirectory)
        {
            DirectoryInfo oldDirectoryInfo = new DirectoryInfo(oldDirectory);
            DirectoryInfo newDirectoryInfo = new DirectoryInfo(newDirectory);


            if (!Directory.Exists(newDirectory))
                Directory.CreateDirectory(newDirectory);


            FileInfo[] fileArr = oldDirectoryInfo.GetFiles();
            foreach (FileInfo fileInfo in fileArr)
            {
                string newFilePath = newDirectory + @"\" + fileInfo.Name;
                try
                {
                    if (File.Exists(newFilePath))
                        File.Delete(newFilePath);
                    fileInfo.CopyTo(newFilePath, true);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Copy Fail:" + fileInfo.FullName);
                }
            }

            DirectoryInfo[] directArr = oldDirectoryInfo.GetDirectories();
            foreach (DirectoryInfo directInfo in directArr)
            {
                CopyDirectory(directInfo.FullName, newDirectory + @"\" + directInfo.Name);
            }
        }

        #endregion
    }

}
